<template>
  <div class="behavior-statistics">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>用户行为分析</span>
          <el-button-group>
            <el-button type="primary" @click="refreshData">刷新数据</el-button>
            <el-button type="success" @click="exportData">导出数据</el-button>
          </el-button-group>
        </div>
      </template>

      <!-- 时间范围选择 -->
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="统计时间">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :shortcuts="dateShortcuts"
            @change="handleDateChange"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 统计卡片 -->
      <el-row :gutter="20" class="data-overview">
        <el-col :span="6">
          <el-card shadow="hover">
            <template #header>
              <div class="card-header-small">
                <span>日活跃用户</span>
                <el-tag size="small">{{ percentageChange.dau }}%</el-tag>
              </div>
            </template>
            <div class="card-value">{{ statistics.dau }}</div>
            <div class="card-compare">环比：{{ statistics.dauGrowth }}%</div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover">
            <template #header>
              <div class="card-header-small">
                <span>月活跃用户</span>
                <el-tag size="small">{{ percentageChange.mau }}%</el-tag>
              </div>
            </template>
            <div class="card-value">{{ statistics.mau }}</div>
            <div class="card-compare">环比：{{ statistics.mauGrowth }}%</div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover">
            <template #header>
              <div class="card-header-small">
                <span>平均停留时长</span>
                <el-tag size="small"
                  >{{ percentageChange.avgStayTime }}%</el-tag
                >
              </div>
            </template>
            <div class="card-value">{{ statistics.avgStayTime }}分钟</div>
            <div class="card-compare">
              环比：{{ statistics.avgStayTimeGrowth }}%
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover">
            <template #header>
              <div class="card-header-small">
                <span>跳出率</span>
                <el-tag
                  size="small"
                  :type="percentageChange.bounceRate > 0 ? 'danger' : 'success'"
                >
                  {{ percentageChange.bounceRate }}%
                </el-tag>
              </div>
            </template>
            <div class="card-value">{{ statistics.bounceRate }}%</div>
            <div class="card-compare">
              环比：{{ statistics.bounceRateGrowth }}%
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 图表区域 -->
      <div class="charts-container">
        <el-row :gutter="20">
          <el-col :span="16">
            <el-card class="chart-card">
              <template #header>
                <div class="chart-header">
                  <span>用户活跃趋势</span>
                  <el-radio-group v-model="activeType" size="small">
                    <el-radio-button label="dau">日活</el-radio-button>
                    <el-radio-button label="wau">周活</el-radio-button>
                    <el-radio-button label="mau">月活</el-radio-button>
                  </el-radio-group>
                </div>
              </template>
              <div ref="activeChart" class="chart"></div>
            </el-card>
          </el-col>
          <el-col :span="8">
            <el-card class="chart-card">
              <template #header>
                <div class="chart-header">
                  <span>用户访问时段分布</span>
                </div>
              </template>
              <div ref="timeChart" class="chart"></div>
            </el-card>
          </el-col>
        </el-row>
        <el-row :gutter="20" class="mt-4">
          <el-col :span="12">
            <el-card class="chart-card">
              <template #header>
                <div class="chart-header">
                  <span>页面访问排行</span>
                </div>
              </template>
              <div ref="pageChart" class="chart"></div>
            </el-card>
          </el-col>
          <el-col :span="12">
            <el-card class="chart-card">
              <template #header>
                <div class="chart-header">
                  <span>用户行为路径</span>
                </div>
              </template>
              <div ref="pathChart" class="chart"></div>
            </el-card>
          </el-col>
        </el-row>
      </div>

      <!-- 用户行为明细 -->
      <el-card class="mt-4">
        <template #header>
          <div class="detail-header">
            <span>行为明细</span>
          </div>
        </template>
        <el-table v-loading="loading" :data="behaviorList" style="width: 100%">
          <el-table-column prop="sessionId" label="会话ID" width="120" />
          <el-table-column prop="userType" label="用户类型" width="100">
            <template #default="{ row }">
              <el-tag>{{ getUserTypeLabel(row.userType) }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column
            prop="page"
            label="访问页面"
            min-width="200"
            show-overflow-tooltip
          />
          <el-table-column prop="action" label="行为类型" width="120">
            <template #default="{ row }">
              <el-tag :type="getActionType(row.action)">
                {{ getActionLabel(row.action) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="stayTime" label="停留时长" width="120">
            <template #default="{ row }">
              {{ formatStayTime(row.stayTime) }}
            </template>
          </el-table-column>
          <el-table-column prop="device" label="设备类型" width="100">
            <template #default="{ row }">
              <el-tag type="info">{{ getDeviceLabel(row.device) }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="访问时间" width="160" />
        </el-table>

        <!-- 分页 -->
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted, nextTick } from "vue";
import { ElMessage } from "element-plus";
import * as echarts from "echarts";

// 搜索表单
const searchForm = reactive({
  dateRange: [],
});

// 日期快捷选项
const dateShortcuts = [
  {
    text: "最近一周",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
      return [start, end];
    },
  },
  {
    text: "最近一月",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
      return [start, end];
    },
  },
  {
    text: "最近三月",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
      return [start, end];
    },
  },
];

// 统计数据
const statistics = reactive({
  dau: 2860,
  dauGrowth: 15.4,
  mau: 28600,
  mauGrowth: 8.2,
  avgStayTime: 25,
  avgStayTimeGrowth: 6.7,
  bounceRate: 35.8,
  bounceRateGrowth: -2.5,
});

// 环比变化
const percentageChange = reactive({
  dau: 15.4,
  mau: 8.2,
  avgStayTime: 6.7,
  bounceRate: -2.5,
});

// 图表相关
const activeType = ref("dau");
const activeChart = ref(null);
const timeChart = ref(null);
const pageChart = ref(null);
const pathChart = ref(null);
let charts = [];

// 表格数据
const loading = ref(false);
const behaviorList = ref([
  {
    sessionId: "S2024001",
    userType: "visitor",
    page: "首页",
    action: "view",
    stayTime: 120,
    device: "mobile",
    createTime: "2024-03-20 10:00:00",
  },
  {
    sessionId: "S2024002",
    userType: "registered",
    page: "景点详情页",
    action: "click",
    stayTime: 300,
    device: "pc",
    createTime: "2024-03-20 10:15:00",
  },
  {
    sessionId: "S2024003",
    userType: "registered",
    page: "订单确认页",
    action: "order",
    stayTime: 180,
    device: "mobile",
    createTime: "2024-03-20 10:30:00",
  },
  {
    sessionId: "S2024004",
    userType: "visitor",
    page: "酒店列表页",
    action: "search",
    stayTime: 240,
    device: "pc",
    createTime: "2024-03-20 10:45:00",
  },
  {
    sessionId: "S2024005",
    userType: "registered",
    page: "美食推荐页",
    action: "share",
    stayTime: 150,
    device: "mobile",
    createTime: "2024-03-20 11:00:00",
  },
]);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

// 获取用户类型标签
const getUserTypeLabel = (type) => {
  const types = {
    visitor: "游客",
    registered: "注册用户",
    vip: "VIP用户",
  };
  return types[type] || type;
};

// 获取行为类型标签
const getActionLabel = (action) => {
  const actions = {
    view: "浏览",
    search: "搜索",
    click: "点击",
    order: "下单",
    share: "分享",
  };
  return actions[action] || action;
};

// 获取行为类型样式
const getActionType = (action) => {
  const types = {
    view: "info",
    search: "warning",
    click: "success",
    order: "primary",
    share: "danger",
  };
  return types[action] || "";
};

// 获取设备类型标签
const getDeviceLabel = (device) => {
  const devices = {
    pc: "PC端",
    mobile: "移动端",
    tablet: "平板",
  };
  return devices[device] || device;
};

// 格式化停留时长
const formatStayTime = (seconds) => {
  if (seconds < 60) {
    return `${seconds}秒`;
  }
  const minutes = Math.floor(seconds / 60);
  return `${minutes}分${seconds % 60}秒`;
};

// 加载数据
const loadData = () => {
  loading.value = true;
  try {
    // 模拟API调用
    setTimeout(() => {
      // 更新统计数据
      Object.assign(statistics, {
        dau: 2860,
        dauGrowth: 15.4,
        mau: 28600,
        mauGrowth: 8.2,
        avgStayTime: 25,
        avgStayTimeGrowth: 6.7,
        bounceRate: 35.8,
        bounceRateGrowth: -2.5,
      });

      // 更新环比数据
      Object.assign(percentageChange, {
        dau: 15.4,
        mau: 8.2,
        avgStayTime: 6.7,
        bounceRate: -2.5,
      });

      // 更新表格数据
      behaviorList.value = [
        {
          sessionId: "S2024001",
          userType: "visitor",
          page: "首页",
          action: "view",
          stayTime: 120,
          device: "mobile",
          createTime: "2024-03-20 10:00:00",
        },
        {
          sessionId: "S2024002",
          userType: "registered",
          page: "景点详情页",
          action: "click",
          stayTime: 300,
          device: "pc",
          createTime: "2024-03-20 10:15:00",
        },
        {
          sessionId: "S2024003",
          userType: "registered",
          page: "订单确认页",
          action: "order",
          stayTime: 180,
          device: "mobile",
          createTime: "2024-03-20 10:30:00",
        },
        {
          sessionId: "S2024004",
          userType: "visitor",
          page: "酒店列表页",
          action: "search",
          stayTime: 240,
          device: "pc",
          createTime: "2024-03-20 10:45:00",
        },
        {
          sessionId: "S2024005",
          userType: "registered",
          page: "美食推荐页",
          action: "share",
          stayTime: 150,
          device: "mobile",
          createTime: "2024-03-20 11:00:00",
        },
      ];

      // 更新图表数据
      const chartData = {
        active: {
          dates: ["3-14", "3-15", "3-16", "3-17", "3-18", "3-19", "3-20"],
          users: [2500, 2800, 2600, 2900, 2700, 3000, 2860],
          growth: [12.5, 13.2, 12.8, 14.5, 13.8, 15.2, 15.4],
        },
        time: {
          hours: [
            "00:00",
            "03:00",
            "06:00",
            "09:00",
            "12:00",
            "15:00",
            "18:00",
            "21:00",
          ],
          visits: [350, 120, 250, 1560, 1860, 1680, 1980, 1420],
        },
        pages: {
          names: ["首页", "景点详情", "酒店列表", "门票预订", "美食推荐"],
          visits: [2860, 2450, 1980, 1560, 1280],
        },
        path: {
          nodes: [
            { name: "首页" },
            { name: "景点列表" },
            { name: "景点详情" },
            { name: "门票预订" },
            { name: "订单确认" },
            { name: "支付完成" },
          ],
          links: [
            { source: "首页", target: "景点列表", value: 1860 },
            { source: "首页", target: "景点详情", value: 960 },
            { source: "景点列表", target: "景点详情", value: 1280 },
            { source: "景点详情", target: "门票预订", value: 860 },
            { source: "门票预订", target: "订单确认", value: 680 },
            { source: "订单确认", target: "支付完成", value: 580 },
          ],
        },
      };

      // 更新图表
      updateCharts(chartData);

      loading.value = false;
      ElMessage.success("数据加载成功");
    }, 1000);
  } catch (error) {
    console.error("Failed to load data:", error);
    loading.value = false;
    ElMessage.error("数据加载失败");
  }
};

// 更新图表数据
const updateCharts = (data) => {
  // 清理旧图表
  charts.forEach((chart) => {
    if (chart) {
      try {
        chart.dispose();
      } catch (error) {
        console.error("Failed to dispose chart:", error);
      }
    }
  });
  charts = [];

  // 重新初始化图表
  nextTick(() => {
    // 用户活跃趋势图
    if (activeChart.value) {
      const active = echarts.init(activeChart.value);
      const activeOption = {
        tooltip: {
          trigger: "axis",
        },
        legend: {
          data: ["活跃用户数", "同比增长"],
        },
        grid: {
          left: "3%",
          right: "4%",
          bottom: "3%",
          containLabel: true,
        },
        xAxis: {
          type: "category",
          boundaryGap: false,
          data: data.active.dates,
        },
        yAxis: [
          {
            type: "value",
            name: "用户数",
            position: "left",
          },
          {
            type: "value",
            name: "增长率",
            position: "right",
            axisLabel: {
              formatter: "{value}%",
            },
          },
        ],
        series: [
          {
            name: "活跃用户数",
            type: "line",
            smooth: true,
            data: data.active.users,
            itemStyle: {
              color: "#409EFF",
            },
            areaStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: "rgba(64, 158, 255, 0.3)" },
                { offset: 1, color: "rgba(64, 158, 255, 0.1)" },
              ]),
            },
          },
          {
            name: "同比增长",
            type: "line",
            yAxisIndex: 1,
            smooth: true,
            data: data.active.growth,
            itemStyle: {
              color: "#67C23A",
            },
          },
        ],
      };
      active.setOption(activeOption);
      charts.push(active);
    }

    // 访问时段分布图
    if (timeChart.value) {
      const time = echarts.init(timeChart.value);
      const timeOption = {
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "shadow",
          },
        },
        grid: {
          left: "3%",
          right: "4%",
          bottom: "3%",
          containLabel: true,
        },
        xAxis: {
          type: "category",
          data: data.time.hours,
        },
        yAxis: {
          type: "value",
          name: "访问量",
        },
        series: [
          {
            name: "访问量",
            type: "bar",
            data: data.time.visits,
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: "#83bff6" },
                { offset: 0.5, color: "#188df0" },
                { offset: 1, color: "#188df0" },
              ]),
            },
          },
        ],
      };
      time.setOption(timeOption);
      charts.push(time);
    }

    // 页面访问排行图
    if (pageChart.value) {
      const page = echarts.init(pageChart.value);
      const pageOption = {
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "shadow",
          },
        },
        grid: {
          left: "3%",
          right: "4%",
          bottom: "3%",
          containLabel: true,
        },
        xAxis: {
          type: "value",
          name: "访问量",
        },
        yAxis: {
          type: "category",
          data: data.pages.names,
        },
        series: [
          {
            name: "访问量",
            type: "bar",
            data: data.pages.visits,
            itemStyle: {
              color: new echarts.graphic.LinearGradient(1, 0, 0, 0, [
                { offset: 0, color: "#83bff6" },
                { offset: 0.5, color: "#188df0" },
                { offset: 1, color: "#188df0" },
              ]),
            },
          },
        ],
      };
      page.setOption(pageOption);
      charts.push(page);
    }

    // 用户行为路径图
    if (pathChart.value) {
      const path = echarts.init(pathChart.value);
      const pathOption = {
        tooltip: {
          trigger: "item",
        },
        series: [
          {
            type: "sankey",
            layout: "none",
            emphasis: {
              focus: "adjacency",
            },
            data: data.path.nodes,
            links: data.path.links,
          },
        ],
      };
      path.setOption(pathOption);
      charts.push(path);
    }
  });
};

// 刷新数据
const refreshData = () => {
  loadData();
};

// 导出数据
const exportData = () => {
  const data = {
    statistics: { ...statistics },
    behaviorList: [...behaviorList.value],
  };

  // 创建Blob对象
  const blob = new Blob([JSON.stringify(data, null, 2)], {
    type: "application/json",
  });

  // 创建下载链接
  const url = window.URL.createObjectURL(blob);
  const link = document.createElement("a");
  link.href = url;
  link.download = `user_behavior_statistics_${new Date().toISOString().split("T")[0]}.json`;

  // 触发下载
  document.body.appendChild(link);
  link.click();

  // 清理
  document.body.removeChild(link);
  window.URL.revokeObjectURL(url);

  ElMessage.success("数据导出成功");
};

// 日期变化处理
const handleDateChange = () => {
  handleSearch();
};

// 搜索
const handleSearch = () => {
  loadData();
};

// 重置搜索
const resetSearch = () => {
  searchForm.dateRange = [];
  handleSearch();
};

// 分页相关方法
const handleSizeChange = (val) => {
  pageSize.value = val;
  loadData();
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
  loadData();
};

// 页面加载时获取数据
onMounted(() => {
  loadData();

  // 监听窗口大小变化
  window.addEventListener("resize", () => {
    charts.forEach((chart) => {
      if (chart) {
        try {
          chart.resize();
        } catch (error) {
          console.error("Failed to resize chart:", error);
        }
      }
    });
  });
});

// 组件卸载时清理
onUnmounted(() => {
  charts.forEach((chart) => {
    if (chart) {
      try {
        chart.dispose();
      } catch (error) {
        console.error("Failed to dispose chart:", error);
      }
    }
  });

  window.removeEventListener("resize", () => {
    charts.forEach((chart) => chart.resize());
  });
});
</script>

<style scoped>
.behavior-statistics {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 20px;
}

.data-overview {
  margin-bottom: 20px;
}

.card-header-small {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 14px;
}

.card-value {
  font-size: 24px;
  font-weight: bold;
  margin: 10px 0;
}

.card-compare {
  font-size: 12px;
  color: #666;
}

.charts-container {
  margin-top: 20px;
}

.chart-card {
  margin-bottom: 20px;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart {
  height: 300px;
}

.mt-4 {
  margin-top: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>
